package com.fds.system.service;

import com.alibaba.fastjson.JSONObject;
import com.fds.system.config.SecurityProperties;
import com.fds.system.model.LoginUser;
import com.fds.system.utils.JwtTokenUtil;
import com.fds.system.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 获取数据库用户
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    public String login(String username, String password) {
        // 模拟从数据库 获取登录用户
        LoginUser loginUser = new LoginUser("fds", "123");
        loginUser.setId(123L);
        loginUser.setType("people");
        Set authoritiesSet = new HashSet();
        // 模拟从数据库中获取用户权限
        authoritiesSet.add("test:add");
        authoritiesSet.add("test:list");
        authoritiesSet.add("ddd:list");
        loginUser.setCustomAuthorities(authoritiesSet);
        String token = JwtTokenUtil.generateToken(loginUser);
        redisUtil.set(token, JSONObject.toJSONString(loginUser), securityProperties.getExpirationMilliSeconds());
        return token;
    }
}
